<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, ref, onMounted } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTree } from 'element-plus'
import { getAllMenuTreeApi } from '@/api/menu'
import { getRoleDetailApi } from '@/api/role'
import { Log } from '@/utils/logError'
import { listToTree } from '@/utils/tree'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentCode: {
    type: String,
    default: () => null
  }
})

const treeRef = ref<typeof ElTree>()

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: t('role.name'),
    component: 'Input'
  },
  {
    field: 'code',
    label: t('role.code'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Switch'
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      'show-word-limit': true,
      maxlength: 100,
      rows: 4,
      resize: 'none'
    }
  },
  {
    field: 'menu',
    label: t('role.menu'),
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <div class="flex w-full">
              <div class="flex-1">
                <ElTree
                  ref={treeRef}
                  show-checkbox
                  node-key="id"
                  highlight-current
                  default-checked-keys={defaultCheckedKeys.value}
                  expand-on-click-node={false}
                  data={treeData.value}
                  onNode-click={nodeClick}
                >
                  {{
                    default: (data) => {
                      return <span>{t(data.data.title)}</span>
                    }
                  }}
                </ElTree>
              </div>
            </div>
          )
        }
      }
    }
  }
])

const currentTreeData = ref()
const nodeClick = (treeData: any) => {
  currentTreeData.value = treeData
}

const rules = reactive({
  name: [required()],
  code: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref<AppCustomRouteRecordRaw[]>([])
const defaultCheckedKeys = ref<number[]>([])
const getMenuList = async () => {
  try {
    const res = await getAllMenuTreeApi()
    treeData.value = listToTree(res.data || [], { pid: 'parentId' })
  } catch (error) {
    Log.error('getMenuList', error)
  }
}

const getRoleDetail = async () => {
  try {
    if (!props.currentCode) return await setValues({})
    const res = await getRoleDetailApi(props.currentCode)
    defaultCheckedKeys.value = res.data.menuIds || []
    await setValues(res.data)
  } catch (error) {
    Log.error('getRoleDetail', error)
  }
}

onMounted(() => {
  getRoleDetail()
  getMenuList()
})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.menuIds = treeRef.value?.getCheckedKeys() || []
    return formData
  }
}

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" :is-col="false" @register="formRegister" :schema="formSchema" />
</template>
